package com.bnlr.lrparking.appui.stall;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.appui.appoint.SubscribeSucceedActivity;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.event.PaySucceeEvent;
import com.bnlr.lrparking.model.BaseArrayBean;
import com.bnlr.lrparking.model.WantBuyBean;
import com.bnlr.lrparking.view.ChineseEditText;
import com.bnlr.lrparking.view.SampleEditTextWatcher;
import com.bnlr.lrparking.widget.boarddialog.KeyBoardDialog;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * @author hp
 * @date 2017/10/17
 * 远看车位提交信息
 */

public class LookStallSubActivity extends BaseActivity {

    private Unbinder unbinder;
    @BindView(R.id.et_name)
    ChineseEditText etName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.ed_lookstall_time)
    EditText ed_lookstall_time;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.look_stall)
    RelativeLayout look_stall;
    @BindView(R.id.text_count_limit)
    TextView textCountLimit;
    @BindView(R.id.et_publish_description)
    EditText etDescription;
    private String spaceId;
    private String username, publishPhone;
    private int fromTag;
    private WantBuyBean bean;
    private int tag;
    private OptionsPickerView pvOptions;
    private ArrayList<String> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private String[] str1 = {"全天", "上午", "下午", "晚上"};
    private static final long ONE_DAY_MS = 24 * 60 * 60 * 1000; //以天为单位
    private static List<String> list = new ArrayList<>();
    private String textTime="";
    private String describeStr="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lookstallsub);
        EventBus.getDefault().register(this);
        unbinder = ButterKnife.bind(this);
        username = AppConfig.getInstance().getString("userName", "");
        publishPhone = username;
        if (!username.equals("")) {
            tvPhone.setText(username.substring(0, 3) + "****" + username.substring(7));
        }
        initView();
    }

    @OnClick({R.id.id_submit, R.id.tv_phone, R.id.submit_rl, R.id.ed_lookstall_time})
    public void submitMessageClick(View view) {
        switch (view.getId()) {
            case R.id.id_submit:
                list.clear();
                finish();
                break;
            case R.id.tv_phone:
                KeyBoardDialog dialog = new KeyBoardDialog(this, publishPhone);
                dialog.setOnDialogResultListener(new KeyBoardDialog.OnDialogResultListener() {
                    @Override
                    public void onResult(String result) {
                        if (result.equals("some")) {
                            ToastUtils.showShort("此手机号无需再次验证");
                        } else if (!result.equals("fail")) {
                            publishPhone = result;
                            tvPhone.setText(publishPhone.substring(0, 3) + "****" + publishPhone.substring(7));
                        }
                    }
                });
                dialog.show();
                break;
            case R.id.submit_rl:
                if (TextUtils.isEmpty(etName.getText().toString())) {
                    ToastUtils.showShort("请填写联系人");
                    return;
                }
                if (TextUtils.isEmpty(textTime)) {
                    ToastUtils.showShort("请选择时间");
                    return;
                }
                getSubmit();
                break;
            case R.id.ed_lookstall_time:
                pvOptions.show();
                break;
            default:
                break;
        }
    }

    private void initView() {
        getOptionData();
        initOptionPicker();
        Intent intent = getIntent();
        spaceId = intent.getStringExtra("spaceId");
        fromTag = intent.getIntExtra("buy_from", 0);
        bean = new WantBuyBean();
        if (fromTag == 1) {
            bean.setIsByStage(0);
            tag = intent.getIntExtra("typeInt", 0);
        } else if (fromTag == 2) {
            bean.setIsByStage(1);
            bean.setBankId(intent.getIntExtra("bankId", 0));
            bean.setFirstPay(intent.getStringExtra("firstPay"));
            bean.setEachStagePrice(intent.getStringExtra("eachStagePrice"));
            bean.setStageNumber(intent.getIntExtra("stageNumber", 0));
        }
        bean.setSpaceId(spaceId);

        etDescription.addTextChangedListener(new SampleEditTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                describeStr=etDescription.getText().toString();
                int length = s.toString().length();
                textCountLimit.setText(length + "/50");
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCLose(PaySucceeEvent event) {
        finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    private void getSubmit() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
            mRequest.add("action", "AddUserWantSpace");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("spaceId", spaceId);
            mRequest.add("name", etName.getText().toString() + (radioGroup.getCheckedRadioButtonId() == R.id.man ? "先生" : "女士"));
            mRequest.add("phone", publishPhone);
            mRequest.add("isWantLook", "1");
            mRequest.add("timeString", textTime);
            mRequest.add("description", describeStr);

            // 添加到请求队列
            CallServer.getRequestInstance().add(LookStallSubActivity.this, mRequest,
                    new CustomHttpListener<BaseArrayBean>(LookStallSubActivity.this, true, BaseArrayBean.class) {
                        @Override
                        public void doWork(BaseArrayBean data, String code) {
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            if (code.equals("1")) {
                                startActivity(SubscribeSucceedActivity.class);
                            } else {
                                try {
                                    ToastUtils.showShort(obj.getString("msg"));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }, true);
        } catch (Exception e) {
        }
    }

    private void initOptionPicker() {//条件选择器初始化
        /**
         * 注意 ：如果是三级联动的数据(省市区等)，请参照 JsonDataActivity 类里面的写法。
         */
        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                textTime = options1Items.get(options1)
                        + "  " + options2Items.get(options1).get(options2);
                ed_lookstall_time.setText(textTime);
            }
        }).setTitleText("")
                .setContentTextSize(18)//设置滚轮文字大小
                .setDividerColor(getResources().getColor(R.color.line_bg))//设置分割线的颜色
                .setSelectOptions(0, 1)//默认选中项
                .setBgColor(getResources().getColor(R.color.write))
                .setTitleBgColor(getResources().getColor(R.color.bg))
                .setTitleColor(getResources().getColor(R.color.text_color))
                .setCancelColor(getResources().getColor(R.color.text_color))
                .setSubmitColor(getResources().getColor(R.color.text_color))
                .setTextColorCenter(getResources().getColor(R.color.text_color))
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();
        pvOptions.setPicker(options1Items, options2Items);//二级选择器
    }

    private void getOptionData() {
        setTime();
        //选项1
        for (int i = 0; i < list.size(); i++) {
            options1Items.add(list.get(i));
        }
        //选项2
        ArrayList<String> options2Items_01 = new ArrayList<>();
        ArrayList<String> options2Items_02 = new ArrayList<>();
        ArrayList<String> options2Items_03 = new ArrayList<>();
        ArrayList<String> options2Items_04 = new ArrayList<>();
        ArrayList<String> options2Items_05 = new ArrayList<>();
        ArrayList<String> options2Items_06 = new ArrayList<>();
        ArrayList<String> options2Items_07 = new ArrayList<>();
        ArrayList<String> options2Items_08 = new ArrayList<>();
        options2Items_01.add(str1[0]);
        int nowHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
        if (nowHour > 6 && nowHour< 12) {
            for (int i = 0; i < str1.length; i++) {
                options2Items_02.add(str1[i]);
            }
        } else if (nowHour >= 12 && nowHour < 18) {
            options2Items_02.add(str1[2]);
            options2Items_02.add(str1[3]);
        } else {
            options2Items_02.add(str1[3]);
        }
        for (int i = 0; i < str1.length; i++) {
            options2Items_03.add(str1[i]);
            options2Items_04.add(str1[i]);
            options2Items_05.add(str1[i]);
            options2Items_06.add(str1[i]);
            options2Items_07.add(str1[i]);
            options2Items_08.add(str1[i]);
        }
        options2Items.add(options2Items_01);
        options2Items.add(options2Items_02);
        options2Items.add(options2Items_03);
        options2Items.add(options2Items_04);
        options2Items.add(options2Items_05);
        options2Items.add(options2Items_06);
        options2Items.add(options2Items_07);
        options2Items.add(options2Items_08);
    }

    private void setTime() {
        Calendar calendar2 = Calendar.getInstance();
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
        calendar2.add(Calendar.DATE, 6);
        String three_days_after = sdf2.format(calendar2.getTime());
        try {
            betweenDays(System.currentTimeMillis(), sdf2.parse(three_days_after).getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取两个时间戳之间的所有日期
     *
     * @param startTime
     * @param endTime
     */
    private static void betweenDays(long startTime, long endTime) {
        Date date_start = new Date(startTime);
        Date date_end = new Date(endTime);
        //计算日期从开始时间于结束时间的0时计算
        Calendar fromCalendar = Calendar.getInstance();
        fromCalendar.setTime(date_start);
        fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
        fromCalendar.set(Calendar.MINUTE, 0);
        fromCalendar.set(Calendar.SECOND, 0);
        fromCalendar.set(Calendar.MILLISECOND, 0);
        Calendar toCalendar = Calendar.getInstance();
        toCalendar.setTime(date_end);
        toCalendar.set(Calendar.HOUR_OF_DAY, 0);
        toCalendar.set(Calendar.MINUTE, 0);
        toCalendar.set(Calendar.SECOND, 0);
        toCalendar.set(Calendar.MILLISECOND, 0);
        int s = (int) ((toCalendar.getTimeInMillis() - fromCalendar.getTimeInMillis()) / (ONE_DAY_MS));
        if (s > 0) {
            list.add("随时看");
            for (int i = 0; i <= s; i++) {
                long todayDate = fromCalendar.getTimeInMillis() + i * ONE_DAY_MS;
                //获取所有时间
                list.add(getDate(todayDate));
            }
        }
    }

    /**
     * 时间戳换字符串
     *
     * @param time
     * @return
     */
    public static String getDate(long time) {
        Date date = new Date(time);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd  EEEE");
        return format.format(date);
    }


}
